package com.ato.MyCollection.MapTest;

/**
 * @author wangjing
 * @create 2021--11--29--21:37
 */

import java.util.TreeMap;

/**
 * 添加时， key需要是同一类的！！！，因为要按照key排序：比如定制，自然排序
 */
class People implements Comparable {
//    @Override
//    public boolean equals(Object o) {
//        if (this == o) return true;
//        if (o == null || getClass() != o.getClass()) return false;
//        People people = (People) o;
//        return age == people.age && Objects.equals(name, people.name);
//    }
//
//    @Override
//    public int hashCode() {
//        return Objects.hash(name, age);
//    }

    private String name;
    private int age;

    public People() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "People{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public People(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Object o) {
        if (o instanceof People) {
            People p1 = (People) o;
            int i = this.name.compareTo(p1.name);
            if (i == 0) {
                return Integer.compare(this.age, p1.age);
            }
            return i;
        } else {
            throw new RuntimeException("输入类型不正确");
        }
    }
}

public class TreeMapTest {
    public static void main(String[] args) {
        TreeMap treeMap = new TreeMap();
        People p1 = new People("p1", 18);
        People p2 = new People("p2", 318);
        People p3 = new People("p3", 218);

        treeMap.put(p1, "100分");
        treeMap.put(p3, "300分");
        treeMap.put(p2, "200分");
//        遍历时，按照key的顺序排序：这里的key是按照 People的name来排序的
        System.out.println(treeMap);
    }
}
